
#include "sprite.h"

void Sprite_Init (Sprite* sprite, const char filename[], const Vector3f* position, const Color* color, float theta, float phi)
{
	
	unsigned int tex = Texture_LoadTexture(filename,1);
	Sprite_InitWithTextureCoord(sprite,tex,0,0,1,1,position,color,theta,phi);
}

void Sprite_InitBillboard (Sprite* sprite, const char filename[], const Vector3f* position, const Color* color, const Camera* camera)
{
	unsigned int tex = Texture_LoadTexture(filename,1);
	Sprite_InitWithTextureCoord(sprite,tex,0,0,1,1,position,color,camera->theta,camera->phi);
}

void Sprite_InitFromTextureId (Sprite* sprite, unsigned int textureId, const Vector3f* position, const Color* color, float theta, float phi)
{
	Sprite_InitWithTextureCoord(sprite,textureId,0,0,1,1,position,color,theta,phi);
}

void Sprite_InitBillboardFromTextureId (Sprite* sprite, unsigned int textureId, const Vector3f* position, const Color* color, const Camera* camera)
{
	Sprite_InitWithTextureCoord(sprite,textureId,0,0,1,1,position,color,camera->theta,camera->phi);
}

void Sprite_InitWithTextureCoord (Sprite* sprite, unsigned int textureId, float x,float y,float width,float height,const Vector3f* position, const Color* color,float theta,float phi)
{
	sprite->textureId = textureId;
	sprite->x = x;
	sprite->y = y;
	sprite->width = width;
	sprite->height = height;
	sprite->position = *position;
	sprite->color = *color;
	sprite->theta = theta;
	sprite->phi = phi;
}

void Sprite_Draw(Sprite* sprite, const Camera* camera,const float taille)
{
	sprite->theta = camera->theta;
	sprite->phi = camera->phi;
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glEnable(GL_BLEND);
	glDisable(GL_LIGHTING);
	glEnable(GL_TEXTURE_2D);
	glBindTexture(GL_TEXTURE_2D, sprite->textureId);
	glPushMatrix();
		glTranslatef(sprite->position.x,sprite->position.y,sprite->position.z);
		glRotatef(-sprite->theta,0,1,0);
		glRotatef(sprite->phi,0,0,1);
		glColor4ub(sprite->color.r,sprite->color.g,sprite->color.b,sprite->color.a);
		glBegin(GL_QUADS);
				glTexCoord2f(sprite->y, sprite->x); glVertex3f(0,-taille, -taille);
				glTexCoord2f(sprite->y + sprite->height,sprite->x); glVertex3f( 0,-taille, taille);
				glTexCoord2f(sprite->y + sprite->height, sprite->x + sprite->width); glVertex3f( 0, taille, taille);
				glTexCoord2f(sprite->y, sprite->x + sprite->width); glVertex3f( 0, taille, -taille);
		glEnd();
	glPopMatrix();
}

void Sprite_Destroy(Sprite* sprite)
{
	if (sprite->textureId != 0)
		Texture_Destroy(sprite->textureId);
	sprite->textureId = 0;
	sprite->x = 0;
	sprite->y = 0;
	sprite->width = 0;
	sprite->height = 0;
	sprite->theta = 0;
	sprite->phi = 0;
}
